from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs
import json
data = {'result': 'HTTP SERVER OK'}


class MyRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        
        # 发给请求客户端的响应数据
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def do_POST(self):
        # 解析请求的内容
        content_length = int(self.headers.get('Content-Length', 0))
        post_data = self.rfile.read(content_length).decode('utf-8')
        post_params = parse_qs(post_data)
        print("content_length:",content_length)
        print("post_data:",post_data)
        print("post_params:",post_params)
        # 处理POST请求
        # 在这里编写你的处理逻辑
        
        # 返回响应
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.send_header('Access-Control-Allow-Origin','*')
        self.end_headers()
        response = 'POST request received,data is ['+post_data+"]"
        self.wfile.write(bytes(response,"UTF8"))

    def do_OPTIONS(self):
        self.send_response(200, "ok")  # 如果继续ajax的post请求，那么OPTIONS请求必须成功
        self.send_header('Access-Control-Allow-Origin', '*')  # 告知支持跨域
        self.send_header('Access-Control-Allow-Methods', 'GET, POST,OPTIONS')  # 告知ajax支持的方法
        self.send_header("Access-Control-Allow-Headers",
                         "X-Requested-With, Content-Type")  # 注意如果在ajax中指定了Content-Type，那么这里一定要加上，否则，ajax不会发送后续的POST
       

if __name__ == '__main__':
    host = 'localhost'
    port = 8000
    server_address = (host, port)
    httpd = HTTPServer(server_address, MyRequestHandler)
    print(f'Starting server at {host}:{port}')
    httpd.serve_forever()